package org.spring.qq_chat_java.Wsconfig;


import org.spring.qq_chat_java.pojo.SessionBean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


// WebSocket 主处理器
@Component
public class MyWsHandler extends AbstractWebSocketHandler {
    private static Map<String, SessionBean> map;
    private static AtomicInteger userid;
    //初始化
    static{
        userid = new AtomicInteger(0);
        map=new ConcurrentHashMap<>();
    }

    //连接建立
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);

        SessionBean sessionBean = new SessionBean(session, "user" + userid.incrementAndGet(), "user" + userid.get());
        System.out.println(sessionBean.getUserName()+"连接成功");
        map.put(session.getId(), sessionBean);
    }
    //接收消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        System.out.println("接收到消息："+message.getPayload());
        sendMessage(message.getPayload());
    }
//传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if(session.isOpen()){
            session.close();
        }
        map.remove(session.getId());

    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        map.remove(session.getId());
    }
    public static void sendMessage(String message) throws IOException {
        for (SessionBean sessionBean : map.values()) {
            //发送的消息包括信息内容，以及用户id
            sessionBean.getSession().sendMessage(new TextMessage(message));

        }
    }





}
